import api from '@/api';
import store from '@/store';
import { noNeedPermissionRouteNames } from '@/constants';

const noopData = () => ({});

function updateHeader(comp) {
  const { meta } = comp;
  if (meta && meta.title) {
    document.title = `${meta.title}`;
  } else {
    document.title = 'Med Admin';
  }
}

/**
 * 合并异步数据
 */
function applyAsyncData(component) {
  return function(asyncData) {
    const ComponentData = component.data || noopData;
    // Prevent calling this method for each request on SSR context
    component.data = function() {
      const data = ComponentData.call(this);
      return { ...data, ...asyncData };
    };

    if (component._Ctor && component._Ctor[0].options) {
      component._Ctor[0].options.data = component.data;
    }
  };
}

export default function(router) {
  router.beforeEach((to, from, next) => {
    if (!noNeedPermissionRouteNames.includes(to.name)) {
      store.dispatch('authCheck', to).then(res => {
        if (!res.isLogin) {
          // next('/login');
          next();
        } else if (!res.isAllow) {
          next('/');
        } else {
          next();
        }
      });
    } else {
      next();
    }
  });

  // 数据请求
  router.beforeResolve((to, from, next) => {
    const matched = router.getMatchedComponents(to);
    const prevMatched = router.getMatchedComponents(from);

    let diffed = false;
    const activated = matched.filter((c, i) => {
      return diffed || (diffed = prevMatched[i] !== c);
    });

    if (!activated.length) {
      return next();
    }
    //TODO 进入路由提前预加载数据
    Promise.all(
      activated.map(comp => {
        if (comp.asyncData) {
          return comp.asyncData(api, to, store).then(applyAsyncData(comp));
        }
      }),
    )
      .then(() => {
        // stop loading indicator
        next();
      })
      .catch(() => {
        next();
      });

    if (matched.length) {
      updateHeader(matched[matched.length - 1]);
    }
  });
}
